package com.zhongshengnetwork.rightbe.my.model;

/**
 * Created by zhongsheng-luojianlan on 16/12/31.
 */

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.ProgressDialog;
import android.os.Environment;

import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.utils.ToastUtil;
import com.zhongshengnetwork.rightbe.lang.activity.LangPublishActivity;

public class DownLoadManager {
    public static File getFileFromServer(String path, ProgressDialog pd) throws Exception{
        //如果相等的话表示当前的sdcard挂载在手机上并且是可用的
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            try {
                URL url = new URL(path);
                HttpURLConnection conn =  (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(5000);
                int mb = 1024*1024;
                //获取到文件的大小
                pd.setMax(conn.getContentLength()/mb);
                InputStream is = conn.getInputStream();
                File file = new File(CommonUtils.getFile(Environment.DIRECTORY_PICTURES), "updata.apk");
                FileOutputStream fos = new FileOutputStream(file);
                BufferedInputStream bis = new BufferedInputStream(is);
                byte[] buffer = new byte[1024];
                int len ;
                int total=0;
                while((len =bis.read(buffer))!=-1){
                    fos.write(buffer, 0, len);
                    total+= len;
                    //获取当前下载量
                    pd.setProgress(total/mb);
                }
                fos.close();
                bis.close();
                is.close();
                return file;
            }catch (Exception e){
                LangPublishActivity.uploadError("从设置升级报错："+e.getLocalizedMessage());
                ToastUtil.show(CustomApplication.mContext, "亲，请在设置里面允许【微句】读写SD卡权限后才能升级哦~");
                return null;
            }
        }
        else{
            return null;
        }
    }
}
